<template>
    <div v-loading="loading" class="w-full">
        <SavePage :title="title">
            <template slot="buttons">
                <BaseButton @click="submit('ruleForm')">保存</BaseButton>
            </template>
            <template slot="body">
                <TitleTips title="基础信息" />
                <el-form ref="ruleForm" :model="ruleForm" :rules="rules" size="medium" label-width="100px">
                    <el-row :gutter="24">
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="事发时间" prop="trafficTime">
                                <el-date-picker
                                    v-model="ruleForm.trafficTime"
                                    type="datetime"
                                    placeholder="请选择时间"
                                    style="width: 100%"
                                    format="yyyy-MM-dd HH:mm"
                                    value-format="yyyy-MM-dd HH:mm"
                                    clearable
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="事件类型" prop="type">
                                <el-select v-model="ruleForm.type" clearable placeholder="请选择" style="width: 100%">
                                    <el-option v-for="(value, key) in EventTypes" :key="key" :label="value" :value="parseInt(key, 10)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="事件等级" prop="level">
                                <el-select v-model="ruleForm.level" clearable placeholder="请选择" style="width: 100%">
                                    <el-option v-for="(value, key) in EventLevel" :key="key" :label="value" :value="parseInt(key, 10)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :xl="6" :lg="8">
                            <el-form-item label="事发地点">
                                <el-input v-model="ruleForm.location" placeholder="请选择" @focus="focusLocation" />
                                <AddressMap v-if="showMap" ref="addressDialog" :location="mapLocation" @handdata="getlatandlng" />
                            </el-form-item>
                        </el-col> -->
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="所属公路" prop="roadCode">
                                <RoadSelect :value.sync="ruleForm.roadCode" :stake.sync="ruleForm.roadStake" @change="getRoadName" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="方向" prop="direction">
                                <el-select v-model="ruleForm.direction" placeholder="请选择" clearable style="width: 100%" @change="resetLocation">
                                    <el-option v-for="d in DirectionTwoWayOptions" :key="d.value" :label="d.label" :value="d.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="事发地点" prop="locationType">
                                <el-select
                                    v-model="ruleForm.locationType"
                                    :disabled="!ruleForm.roadCode || !ruleForm.direction"
                                    placeholder="请选择"
                                    style="width: 100%"
                                    @change="resetLocation"
                                >
                                    <el-option v-for="item in locationOptions" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col v-if="ruleForm.locationType === 1" :xl="6" :lg="8">
                            <el-form-item label="设施名称" prop="facilityCode">
                                <!-- <FacilitySelect :value.sync="ruleForm.facilityCode" :props="facilityProps" :params="params" @change="getFacilityName" /> -->
                                <NewFacilitySelect
                                    :value.sync="ruleForm.facilityCode"
                                    :params="params"
                                    :lng-lat.sync="ruleForm.lngLatList"
                                    clearable
                                    @change="getFacilityName"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col v-if="ruleForm.locationType === 2" :xl="6" :lg="8">
                            <el-col :span="14" style="padding: 0">
                                <el-form-item class="spe-item" label="桩号" prop="stake1">
                                    <el-input
                                        v-model.trim="ruleForm.stake1"
                                        :disabled="!ruleForm.roadCode || !ruleForm.direction"
                                        placeholder="请输入"
                                        maxlength="3"
                                        @change="ruleForm.stake2 = ''"
                                    >
                                        <div slot="prepend" class="input-unit">K</div>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10" style="padding: 0">
                                <el-form-item
                                    class="spe-item"
                                    label-width="30px"
                                    label="+"
                                    prop="stake2"
                                    :rules="useCheckStake(ruleForm.roadCode, ruleForm.direction, ruleForm.stake1, ruleForm.roadStake)"
                                >
                                    <el-input v-model.trim="ruleForm.stake2" maxlength="3" :disabled="!ruleForm.stake1" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-col>

                        <el-col v-if="ruleForm.locationType === 3" :xl="12" :lg="16">
                            <el-col :span="7" style="padding: 0">
                                <el-form-item class="spe-item" label="桩号范围" prop="startStake1">
                                    <el-input
                                        v-model.trim="ruleForm.startStake1"
                                        :disabled="!ruleForm.roadCode || !ruleForm.direction"
                                        placeholder="请输入"
                                        maxlength="3"
                                        @change="ruleForm.endStake1 = ''"
                                    >
                                        <div slot="prepend" class="input-unit">K</div>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5" style="padding: 0">
                                <el-form-item
                                    class="spe-item"
                                    label-width="30px"
                                    label="+"
                                    prop="endStake1"
                                    :rules="useCheckStake(ruleForm.roadCode, ruleForm.direction, ruleForm.startStake1, ruleForm.roadStake)"
                                >
                                    <el-input v-model.trim="ruleForm.endStake1" :disabled="!ruleForm.startStake1" maxlength="3" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="7" style="padding: 0">
                                <el-form-item class="spe-item" label-width="50px" label="~" prop="startStake2">
                                    <el-input
                                        v-model.trim="ruleForm.startStake2"
                                        :disabled="!ruleForm.roadCode || !ruleForm.direction"
                                        placeholder="请输入"
                                        maxlength="3"
                                        @change="ruleForm.endStake2 = ''"
                                    >
                                        <div slot="prepend" class="input-unit">K</div>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5" style="padding: 0">
                                <el-form-item
                                    class="spe-item"
                                    label-width="30px"
                                    label="+"
                                    prop="endStake2"
                                    :rules="useCheckStake(ruleForm.roadCode, ruleForm.direction, ruleForm.startStake2, ruleForm.roadStake)"
                                >
                                    <el-input v-model.trim="ruleForm.endStake2" :disabled="!ruleForm.startStake2" maxlength="3" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="上报人员">
                                <el-input v-model.trim="ruleForm.reportUserName" readonly disabled></el-input>
                            </el-form-item>
                        </el-col>
                            <el-col :xl="6" :lg="8">
                            <el-form-item label="上报部门" prop="reportDep">
                                <el-select v-model="ruleForm.reportDep" :disabled="depOptions.length === 0" clearable placeholder="请选择" style="width: 100%">
                                    <el-option v-for="item in depOptions" :key="item.id" :label="item.name" :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="事发原因">
                                <el-input
                                    v-model="ruleForm.reason"
                                    clearable
                                    type="textarea"
                                    maxlength="200"
                                    show-word-limit
                                    placeholder="请输入"
                                    :autosize="{ minRows: 6, maxRows: 10 }"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="是否起火" prop="fire">
                                <el-radio-group v-model="ruleForm.fire">
                                    <el-radio :label="0">否</el-radio>
                                    <el-radio :label="1">是</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item v-if="ruleForm.fire" label="情况描述" class="flex-1">
                                <el-input
                                    v-model="ruleForm.fireDesc"
                                    clearable
                                    maxlength="100"
                                    show-word-limit
                                    style="width: 100%"
                                    type="textarea"
                                    placeholder="请输入"
                                    :autosize="{ minRows: 4, maxRows: 10 }"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="是否爆炸" prop="explosion">
                                <el-radio-group v-model="ruleForm.explosion">
                                    <el-radio :label="0">否</el-radio>
                                    <el-radio :label="1">是</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item v-if="ruleForm.explosion" label="情况描述" class="flex-1">
                                <el-input
                                    v-model="ruleForm.explosionDesc"
                                    clearable
                                    maxlength="100"
                                    show-word-limit
                                    style="width: 100%"
                                    type="textarea"
                                    placeholder="请输入"
                                    :autosize="{ minRows: 4, maxRows: 10 }"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="是否有污染物" prop="pollutant">
                                <el-radio-group v-model="ruleForm.pollutant">
                                    <el-radio :label="0">否</el-radio>
                                    <el-radio :label="1">是</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item v-if="ruleForm.pollutant" label="情况描述" class="flex-1">
                                <el-input
                                    v-model="ruleForm.pollutantDesc"
                                    clearable
                                    maxlength="100"
                                    show-word-limit
                                    style="width: 100%"
                                    type="textarea"
                                    placeholder="请输入"
                                    :autosize="{ minRows: 4, maxRows: 10 }"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="是否有散落物" prop="fallOut">
                                <el-radio-group v-model="ruleForm.fallOut">
                                    <el-radio :label="0">否</el-radio>
                                    <el-radio :label="1">是</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item v-if="ruleForm.fallOut" label="情况描述" class="flex-1">
                                <el-input
                                    v-model="ruleForm.fallOutDesc"
                                    clearable
                                    maxlength="100"
                                    show-word-limit
                                    style="width: 100%"
                                    type="textarea"
                                    placeholder="请输入"
                                    :autosize="{ minRows: 4, maxRows: 10 }"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="上传图片">
                                <el-upload
                                    :action="action"
                                    :headers="headers"
                                    :accept="accept"
                                    :limit="limit"
                                    list-type="picture-card"
                                    multiple
                                    :file-list="fileList"
                                    :before-upload="beforeUpload"
                                    :on-exceed="handleExceed"
                                    :on-success="handleSuccess"
                                    :on-preview="handlePicturePreview"
                                    :on-remove="handleRemove"
                                >
                                    <i class="el-icon-plus" />
                                </el-upload>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="是否路产赔偿" prop="roadCompensation">
                                <el-radio-group v-model="ruleForm.roadCompensation">
                                    <el-radio :label="0">否</el-radio>
                                    <el-radio :label="1">是</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <IndemnifyForm v-if="ruleForm.roadCompensation" ref="indemnify" v-model="compensationContent" />
                        </el-col>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="" />
                        </el-dialog>
                    </el-row>
                </el-form>
            </template>
        </SavePage>
    </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import useSuccess from '@/hooks/useSuccess'
import { mapState } from 'vuex'
import { UploadOption, DirectionTwoWayOptions, LocationOptions } from '@/config/constants'
import { EventLevel, EventTypes } from '@/views/maintenance-decision/constants'
import IndemnifyForm from './components/IndemnifyForm'
import useCheckStake from '@/hooks/useCheckStake'
import { fileTokenKey } from '@/config/settings'
import { isInteger } from '@/utils/validate'
// import AddressMap from './components/AddressMap'
export default {
    components: {
        // AddressMap,
        IndemnifyForm
    },
    data() {
        return {
            EventTypes,
            EventLevel,
            DirectionTwoWayOptions,
            locationOptions: LocationOptions,
            showMap: false,
            id: null,
            number: null,
            limit: UploadOption.LIMIT,
            action: UploadOption.ACTION,
            accept: UploadOption.ACCEPT,
            fileList: [],
            dialogImageUrl: null,
            dialogVisible: false,
            dialog: true,
            poi: null,
            headers: {
                [fileTokenKey]: getToken()
            },
            compensationContent: {},
            ruleForm: {
                lngLatList: [],
                roadStake: '',
                trafficTime: null,
                locationType: 1,
                type: null,
                level: null,
                location: null,
                road: null,
                direction: null,
                facilityCode: [],
                fire: 0,
                explosion: 0,
                pollutant: 0,
                fallOut: 0,
                roadCompensation: 0,
                stake1: '',
                stake2: '',
                startStake1: '',
                endStake1: '',
                startStake2: '',
                endStake2: '',
                reportUserName: this.$store.getters.avatar.name,
                reportUser: this.$store.getters.avatar.id,
                reportDep: ''
            },
            facilityProps: {
                value: 'id',
                label: 'name'
            },
            rules: {
                trafficTime: [{ required: true, message: '请选择事发时间', trigger: 'change' }],
                type: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
                level: [{ required: true, message: '请选择事件等级', trigger: 'change' }],
                roadCode: [{ required: true, message: '请选择所属公路', trigger: 'change' }],
                direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
                locationType: [{ required: true, message: '请选择事发地点', trigger: 'change' }],
                facilityCode: [{ required: true, message: '请选择设施名称', trigger: 'change' }],
                stake1: [
                    { required: true, message: '请输入桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ],
                stake2: [{ required: true, message: '请输入桩号', trigger: 'blur' }],
                startStake1: [
                    { required: true, message: '请输入起点桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ],
                endStake1: [{ required: true, message: '请输入起点桩号', trigger: 'blur' }],
                startStake2: [
                    { required: true, message: '请输入终点桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ],
                endStake2: [{ required: true, message: '请输入终点桩号', trigger: 'blur' }],
                reportDep: [{ required: true, message: '请选择上报部门', trigger: 'change' }]
            },
            depOptions: []
        }
    },
    computed: {
        ...mapState(['loading', 'raods']),
        title() {
            return this.id ? `编辑事件${this.number}` : '新增事件录入'
        },
        photos() {
            return this.fileList
                ?.map((file) => {
                    return file?.response?.data ? file?.response?.data.objectUrl : file.url
                })
                .join(',')
        },
        mapLocation() {
            const locationArr = this.ruleForm?.location?.split(',') || ['103.719279', '27.339359']
            return {
                lng: locationArr[0],
                lat: locationArr[1]
            }
        },
        // 设施的过滤参数
        params() {
            const params = {
                roadCode: this.ruleForm.roadCode,
                direction: this.ruleForm.direction
            }
            return params
        }
    },
    created() {
        this.getDeatil()
        this.depOptions = this.$store.getters.avatar.depart || []
        if (this.depOptions.length > 0) {
            this.ruleForm.reportDep = this.depOptions[0].id
        }
    },
    methods: {
        validNum(rule, value, callback) {
            if (value && !isInteger(value)) {
                callback(new Error('请输入数字'))
            } else {
                callback()
            }
        },
        resetLocation() {
            this.$refs['ruleForm'].clearValidate(['facilityCode', 'stake1', 'stake2', 'startStake1', 'endStake1', 'startStake2', 'endStake2'])
            // this.$set(this.ruleForm, 'facilityCode', [])
            this.ruleForm.facilityCode = []
            this.ruleForm.stake1 = ''
            this.ruleForm.stake2 = ''
            this.ruleForm.startStake1 = ''
            this.ruleForm.endStake1 = ''
            this.ruleForm.startStake2 = ''
            this.ruleForm.endStake2 = ''
        },
        async getDeatil() {
            this.id = +this.$route.query.id
            this.number = this.$route.query.number
            if (this.id) {
                const res = await this.$store.dispatch('trafficIncident/detail', { id: this.id })
                const { compensationContent, ...form } = res
                this.compensationContent = compensationContent
                this.ruleForm = form
                // 需要强制更新下桩号
                this.$set(this.ruleForm, 'stake1', this.ruleForm.stake ? this.ruleForm.stake.split('+')[0].replace('K', '') : '')
                this.$set(this.ruleForm, 'stake2', this.ruleForm.stake ? this.ruleForm.stake.split('+')[1] : '')

                this.ruleForm.facilityCode = [this.ruleForm.facilityType, this.ruleForm.facilityCode]
                this.ruleForm.lngLatList = this.ruleForm.lngLat ? this.ruleForm.lngLat.split(',') : []
                // 处理返回图片列表显示
                this.fileList = this.ruleForm?.photos?.split(',').map((p) => {
                    return {
                        url: p
                    }
                })
            }
        },
        submit(formName) {
            let isValid = true
            this.$refs[formName].validate(async (valid) => {
                console.log(valid)
                if (valid) {
                    if (this.ruleForm.roadCompensation) {
                        isValid = await this.$refs.indemnify.submitForm()
                    }
                    if (isValid) {
                        const data = {
                            ...this.ruleForm,
                            fireDesc: this.ruleForm.fire ? this.ruleForm.fireDesc : null,
                            explosionDesc: this.ruleForm.explosion ? this.ruleForm.explosionDesc : null,
                            pollutantDesc: this.ruleForm.pollutant ? this.ruleForm.pollutantDesc : null,
                            fallOutDesc: this.ruleForm.fallOut ? this.ruleForm.fallOutDesc : null,
                            stake: `K${this.ruleForm.stake1}+${this.ruleForm.stake2}`,
                            facilityType: this.ruleForm.facilityCode[0],
                            facilityCode: this.ruleForm.facilityCode[1],
                            photos: this.photos,
                            compensationContent: this.ruleForm.roadCompensation ? this.compensationContent : null,
                            reportDepName: (this.depOptions.find(item => item.id === this.ruleForm.reportDep) || {}).name
                        }
                        await this.$store.dispatch('trafficIncident/saveOrUpdate', data)
                        useSuccess()
                    }
                }
            })
        },
        beforeUpload(file) {
            const isLt10M = file.size / 1024 / 1024 < 10
            if (!isLt10M) {
                this.$message.warning('上传图片大小不能超过10MB!')
            }
            return isLt10M
        },
        handleExceed(files, fileList) {
            if (fileList?.length >= this.limit) {
                this.$message.warning(`已经上${this.limit}张图片，不能再上传了`)
                return
            }
            this.$message.warning(`最多上传 ${this.limit} 张照片，本次选择了 ${files.length} 个照片`)
        },
        handleSuccess(response, file, fileList) {
            this.fileList = fileList
        },
        handleRemove(file, fileList) {
            this.fileList = fileList
        },
        handlePicturePreview(file) {
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        },
        focusLocation() {
            this.showMap = true
            this.$nextTick(() => {
                this.$refs.addressDialog.show()
            })
        },
        // 获取选择的经纬度信息
        getlatandlng(val) {
            this.ruleForm.location = val.lng + ',' + val.lat
        },
        // 后端还要传设施名称字段
        getFacilityName(val, options) {
            // 设施类型中文名字段
            let facilityName = ''
            // 设施的经纬度
            let lngLatMiddle = ''
            options.forEach((item) => {
                item.children.some((m) => {
                    if (val[1] === m.value) {
                        facilityName = m.label
                        lngLatMiddle = m.lngLat
                        return true
                    }
                })
            })
            this.ruleForm.facilityName = facilityName
            this.ruleForm.lngLat = lngLatMiddle
            console.log(this.ruleForm.facilityName)
        },
        // 后端还要传公路名称字段
        getRoadName(val, options) {
            console.log(7711111111)
            this.resetLocation()
            options.some((item) => {
                if (item.code === val) {
                    this.ruleForm.roadName = item.name
                    this.ruleForm.roadStake = item.roadStake
                    return true
                }
            })
        },
        useCheckStake
    }
}
</script>
<style lang="scss" scoped>
.spe-item {
    ::v-deep {
        .el-form-item__label {
            text-align: center;
            padding: 0;
            &::before {
                display: none;
            }
        }
        .el-input,
        .el-input__inner {
            min-width: auto !important;
        }
    }
}
.click-to-select {
    box-sizing: border-box;
    height: 32px;
    width: 100%;
    border: 1px solid #ccc;
    margin-top: 2px;
    border-radius: 5px;
    line-height: 32px;
    text-align: center;
    cursor: pointer;
    color: #0162ff;
}
.haslatandlng {
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    height: 32px;
    width: 100%;
    border: 1px solid #ccc;
    margin-top: 2px;
    border-radius: 5px;
    line-height: 32px;
    padding: 0 10px;
}
</style>
